<template>
	<div class="news_manage">
		<el-row style="margin-bottom: 8px;">
			<el-col>
				<el-button type="danger" icon="delete" @click="deleteAll" :disabled="deleteIds.length == 0">批量删除</el-button>
				<el-button type="success" icon="plus" @click="modelShow = !modelShow">新增</el-button>
				<el-button type="primary" icon="refresh" @click="reload">刷新</el-button>
			</el-col>
		</el-row>
		<el-table :data="newsList" border @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="80"/>
			<el-table-column type="index" width="80"/>
			<el-table-column label="标题" prop="title"/>
			<el-table-column label="封面" prop="cover_image">
				<template #default="{row}">
					<el-image :src="`/api/${row.cover_image}`" style="width: 100%;"/>
				</template>
			</el-table-column>
			<el-table-column label="分类" prop="category"/>
			<el-table-column label="浏览次数" prop="view_count"/>
			<el-table-column label="点赞次数" prop="like_count"/>
			<el-table-column label="评论数" prop="comment_count"/>
			<el-table-column label="操作" width="150" align="center">
				<template #default="{row}">
					<el-button type="danger" size="small" @click="deleteNews(row.id)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<div style="margin-top: 8px; display: flex; justify-content: flex-end;">
			<el-pagination background layout="prev, pager, next" :total="total" @current-change="pageChange"/>
		</div>
	</div>

	<el-dialog :title="newDetail?.id ? '编辑' : '新增'" v-model="modelShow" top="10" align-center destroy-on-close @close="dialogClose">
		<el-form :rules="rules" :model="newDetail">

			<el-row :gutter="24">
				<el-col :span="12">
					<el-form-item label="标题" prop="title">
						<el-input v-model="newDetail.title"/>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="分类" prop="category">
						<el-input v-model="newDetail.category"/>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row :gutter="24">
				<el-col :span="23">
					<el-form-item label="封面" prop="category">
						<AvatarUploader  v-model="newDetail.cover_image"/>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row :gutter="24">
				<el-col :span="24">
					<el-form-item label="内容" prop="content">
						<Toolbar
							style="border-bottom: 1px solid #ccc; width: 100%;"
							:editor="editorRef"
							:defaultConfig="toolbarConfig"
							mode="default"
						/>
						<textarea ref="editorTextarea" id="editorTextarea" style="display: none;"></textarea>
						<Editor
							style="height: 500px;width: 100%; overflow-y: hidden; border: 1px #333333 solid;"
							v-model="newDetail.content"
							:defaultConfig="editorConfig"
							mode="default"
							@onCreated="handleCreated"
						/>
					</el-form-item>
				</el-col>
			</el-row>

		</el-form>
		<template #footer>
			<el-button @click="modelShow = !modelShow">取消</el-button>
			<el-button type="primary" @click="addNews">确定</el-button>
		</template>
	</el-dialog>
</template>
<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted ,reactive} from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import {categories, news_list,add_news, del_news} from '/@/api/news'
import {ElMessage,ElMessageBox } from "element-plus";
import AvatarUploader from '/@/components/Avatar_Uploader/Index.vue'
import axios from 'axios'
//富文本编辑器实例配置
const editorRef = ref(null)
const editorTextarea = ref(null)
const toolbarConfig = {}
const editorConfig = {
	placeholder: '请输入内容...',
	textarea: '#editorTextarea',
	MENU_CONF: {
		uploadImage: {
			customUpload: async (file, insertFn) => {
				try {
					const formData = new FormData()
					formData.append('file', file)
					// 使用 axios 发送上传请求
					const response = await axios.post('/api/hzadmin/public/upload_image/', formData, {
						headers: {
							'Content-Type': 'multipart/form-data'
						}
					});

					// 成功处理
					const imageUrl = response.data;
					insertFn(`/api/${imageUrl}`);
					ElMessage.success('图片上传成功');
				} catch (error) {
					// 错误处理
					let errorMessage = '图片上传失败：未知错误';
					if (error.response) {
						errorMessage = `图片上传失败：${error.response.data.msg || '接口返回错误'}`;
					} else if (error.request) {
						errorMessage = '图片上传失败：请求未得到响应';
					} else {
						errorMessage = `图片上传失败：${error.message}`;
					}
					ElMessage.error(errorMessage);
				}
			}
		}
	}
}
const handleCreated = (editor) => {
	editorRef.value = editor // 记录 editor 实例，重要！
}
//弹窗显示
const modelShow = ref(false)
//修改、编辑新闻绑定数据
const newDetail = ref({
	title: '', //标题
	content: '', //内容
	category: '',//分类
	cover_image: '' //封面
})


//关闭弹窗
const dialogClose = ()=> {
	newDetail.value = {
		title: '', //标题
		content: '', //内容
		category: '',//分类
	}
	modelShow.value = false
}

//删除新闻
const deleteNews = async id => {
	await ElMessageBox.confirm(
		'确认删除该新闻?',
		'Warning',
		{confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning',}
	)
	const res = await del_news(id)
	ElMessage({
		message: res.msg,
		type: res.code == 200 ? 'success' :'warning',
		duration: 2000
	})
	reload()
}

//添加、修改新闻
const addNews = async ()=> {
	let msg = ''
	msg = !newDetail.value.title ? '请输入标题' : ''
	msg = !newDetail.value.content ? '请输入内容' : ''
	msg = !newDetail.value.category ? '请输入分类' : ''
	msg = !newDetail.value.cover_image ? '请上传封面' : ''
	if(msg){
		ElMessage({
			message: msg,
			type: 'warning',
			duration: 2000
		})
		return
	}
	let res = await add_news(newDetail.value)
	ElMessage({
		message: res.msg,
		type: res.code == 200 ? 'success' :'warning',
		duration: 2000
	})
	modelShow.value = false
	reload()
}


//新闻列表
const newsList = ref([])
const total = ref(0)
const newsListParams = reactive({
	page: 1,
	page_size: 10,
	keyword: '',
	category: ''
})
const getNewsList = async ()=> {
	const res = await news_list(newsListParams)
	newsList.value = res.data.news
	total.value = res.data.total
}

//新闻类别
const newsClass = ref([])
const getNewsClass = async ()=> {
	const res = await categories()
	newsClass.value = res.data.categories
}

const init = ()=> {
	getNewsClass()
	getNewsList()
}
init()

//多选删除
const deleteIds = ref([])
const deleteAll = async() => {
	await ElMessageBox.confirm(
		'确认删除所选新闻?',
		'Warning',
		{confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning',}
	)
	try{
		let count = 0
		for(const id of deleteIds.value){
			await del_news(id)
			count++
		}
		ElMessage({
			message: `已删除${count}条新闻。`,
			type: 'success',
			duration: 2000
		})
		deleteIds.value = []
	}catch (e){
		ElMessage({
			message: '发生错误，请联系管理员!',
			type: 'error',
			duration: 2000
		})
	}
	reload()

}
const handleSelectionChange = (e)=> {
	deleteIds.value = e.map(item => item.id)
}

const reload = () => {
	newsListParams.page = 1
	newsListParams.page_size = 10
	newsListParams.keyword = ''
	newsListParams.category = ''
	getNewsList()
}


const rules = reactive({
	title: [{ required: true, message: '请输入标题!', trigger: 'blur' }],
	category: [{ required: true, message: '请输入分类!', trigger: 'blur' }],
	content: [{ required: true, message: '请输入内容!', trigger: 'blur' }],
})


onBeforeUnmount(() => {
	const editor = editorRef.value
	if (editor == null) return
	editor.destroy()
})

const pageChange = page => {
	newsListParams.page = page
	getNewsList()
}
</script>
<style scoped lang="scss">
.news_manage{
	width: 100%;
	scrollbar-width: none; /* Firefox 64+ */
	-ms-overflow-style: none; /* IE 10+ / Edge */

}
</style>
